package com.sm.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sm.auth.entity.UmsMenu;
import com.sm.auth.entity.UmsRole;
import com.sm.auth.mapper.MenuMapper;
import com.sm.auth.mapper.UserMapper;
import com.sm.auth.service.MenuService;
import com.sm.auth.utils.SecurityUtil;
import com.sm.auth.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, UmsMenu> implements MenuService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public List<UmsMenu> searchSelfMenu() {
        LoginUserVo currentUser = SecurityUtil.getCurrentUser();
        List<Long> roleIds = currentUser.getUmsSysUser().getRoleList().stream().map(UmsRole::getRoleId).collect(Collectors.toList());
        List<UmsMenu> menuList = userMapper.selectMenuByRoleIds(roleIds);
        //递归算法
        List<UmsMenu> trees = new ArrayList<>();
        for (UmsMenu umsMenu : menuList) {
            //if为true即代表是第一级
            if (umsMenu.getParentId() == 0) {
                trees.add(findChildren(umsMenu,menuList));
            }
        }
        return trees;
    }
    //通过递归获取子菜单
    private UmsMenu findChildren(UmsMenu umsMenu, List<UmsMenu> sysMenuList) {
        umsMenu.setChildren(new ArrayList<>());
        for (UmsMenu it : sysMenuList) {
            //即当前菜单的id值与所有菜单的parent_id值相等
            if(umsMenu.getId().equals(it.getParentId())) {
                umsMenu.getChildren().add(findChildren(it,sysMenuList));
            }
        }
        return umsMenu;
    }
}
















